package com.ruipeng.utils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by tu_pei on 17/6/6.
 */
public class HttpUtils {



    /**
     * 向指定 URL 发送POST方法的请求
     * @param url 发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式或者为json字符串。
     * @return 所代表远程资源的响应结果
     */
    public static String sendHttpPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {

            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setReadTimeout(20000);
            conn.setConnectTimeout(20000);
            // 获取URLConnection对象对应的输出流
            //注意修改  请求格式    xml  json
            conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");

            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        //关闭流
        close(out,in);
        return result;
    }

    public static String sendHttpsPost(String url, String param) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {

            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpsURLConnection conn = getConnection(realUrl,"POST");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setReadTimeout(20000);
            conn.setConnectTimeout(20000);
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");

            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        close(out,in);
        return result;
    }
    private static void close(OutputStreamWriter out, BufferedReader in){
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private static HttpsURLConnection getConnection(URL url, String method)
            throws IOException {
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        return conn;
    }
    public static void main(String[] args){
        System.out.println(sendHttpsPost("https://testv2.acegear.com/auth/sso/wechat/code","code=021Fn6u521tD3N0ugsu52dveu52Fn6um&type=1"));
        //String str = "{\"message\":\"\",\"code\":0,\"body\":\"{\\\"message\\\":\\\"\\\",\\\"code\\\":0,\\\"body\\\":{\\\"userId\\\":10047,\\\"role\\\":\\\"client\\\",\\\"jwt\\\":\\\"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMDA0NyIsInJvbGUiOiJjbGllbnQiLCJpc3MiOiIyNzM4MTJjZC05YThlLTQ1YTAtODczMS01ZTZiMWI0MTVhMGEiLCJleHAiOjE0OTc5NTEwMTd9.ikrj9mdN-krfOgm2fseGBEm4iIi142vLLXs-BPXAkek\\\",\\\"userInfo\\\":{\\\"userId\\\":10047,\\\"nickname\\\":\\\"AG_s9f3e5\\\",\\\"avatar\\\":\\\"https://img.acegear.com/avatars/10047/w150\\\",\\\"background\\\":\\\"https://img.acegear.com/dc756c5e-2ed0-4dd0-a8ce-7ccf48bcf1b8/w700\\\",\\\"gender\\\":1,\\\"province\\\":\\\"Beijing\\\",\\\"title\\\":null,\\\"createAt\\\":1497346217687,\\\"updateAt\\\":1497346217687},\\\"userPhone\\\":{\\\"userId\\\":10047,\\\"phone\\\":null,\\\"verified\\\":false,\\\"createAt\\\":null,\\\"updateAt\\\":null},\\\"userEmail\\\":{\\\"userId\\\":10047,\\\"email\\\":null,\\\"verified\\\":false,\\\"createAt\\\":null,\\\"updateAt\\\":null},\\\"regist\\\":true}}\"}";
        //str =str.replaceAll("\\\\","");
        //JSONObject json = JSONObject.fromObject(str);
        //System.out.println(json);
        //System.out.println(JSONObject.fromObject(json.getString("body")).getString("body"));
       // System.out.println(JSONObject.fromObject(JSONObject.fromObject(JSONObject.fromObject(json.getString("body")).getString("body"))).get("userId"));
    }
}
